<template>
  <div class="app-container">
    <div style="margin-bottom:20px;">

      <el-button @click="menusAdd" type="primary" size="small" class="option-item">
        添加菜单
      </el-button>
      <div class="option-item">
        <el-tag>全部展开</el-tag>
        <el-switch
          v-model="defaultExpandAll"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="reset"
        />
      </div>
    </div>
    <tree-table v-loading="tableLoading"  :default-expand-all="defaultExpandAll" :data="data" :columns="columns" border>
      <template slot="scope" slot-scope="{scope}">
         <el-tag type="info" v-if="scope.row.pid == 0 && scope.row.icon != undefined">
          <svg-icon  :icon-class="scope.row.icon" />
        </el-tag>
        <el-tag>roles: {{ scope.row.roles == undefined || scope.row.roles == '' ? 'all' : scope.row.roles }}</el-tag>
        <el-tag v-if="scope.row.hidden == true" type="danger">hidden: {{ scope.row.hidden == true ? true : false }}</el-tag>
        <el-tag v-else="scope.row.hidden == false" type="success">hidden: {{ scope.row.hidden == true ? true : false }}</el-tag>
      </template>
      <template slot="operation" slot-scope="{scope}">
        <el-button type="primary"  @click="addChirld(scope)">添加子级</el-button>
        <el-button type="primary"  @click="click(scope)">详情</el-button>
        <el-button type="success"  @click="editMenu(scope)">编辑</el-button>
        <el-button type="danger"  @click="deleteMenu(scope)">删除</el-button>
      </template>
    </tree-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑菜单':'新增菜单'">
      <el-form ref="ruleForm" :rules="rules" :model="menusForm" label-width="80px" label-position="left">
        <el-form-item v-show="ParentMenu" label="父级" >
          <el-input v-model="menusForm.pidName" disabled />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="menusForm.title" placeholder="菜单标题" />
        </el-form-item>
        <el-form-item label="路由名称" prop="name">
          <el-input v-model="menusForm.name" placeholder="英文路由名称" />
        </el-form-item>
        <el-form-item label="跳转路由" prop="path">
          <el-input v-model="menusForm.path" placeholder="跳转路由" />
        </el-form-item>
        <el-form-item label="组件别名" prop="component">
          <el-input :disabled="componentDisabled"  placeholder="请输入该菜单的组件路径" v-model="menusForm.component">
          </el-input>
          <el-tag  type="info">默认 Layout 父级, 一般填写子级的组件别名即可 如: @/views/permission/menu 别名:menu</el-tag>
        </el-form-item>

        <el-form-item v-show="ParentMenu == false" label="图标" prop="icon">
          <icons :defaultIcon="menusForm.icon" @IconChoice="getIcon"></icons>
        </el-form-item>

        <el-form-item label="隐藏" prop="icon">
            <el-radio v-model="menusForm.hidden" label="1">是</el-radio>
            <el-radio v-model="menusForm.hidden" label="0">否</el-radio>
        </el-form-item>

        <el-form-item label="角色" prop="roles">
          <el-select style="width:100%" v-model="menusForm.roles" multiple placeholder="请选择角色">
            <el-option
              v-for="item in menuRoles"
              :key="item.id"
              :label="item.name"
              :value="item.key">
            </el-option>
          </el-select>
          <el-tag type="info">当前菜单访问的角色，不填写则所有管理员可以访问</el-tag>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">{{ $t('permission.cancel') }}</el-button>
        <el-button :loading="button_loging" type="primary" @click="confirmMenu('ruleForm')">{{ $t('permission.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import treeTable from '@/components/TreeTable'
import icons from '../icons/index'
import { menuList, updateMenu, addMenu, deleteMenu } from '@/api/permission'
import { getRoleShow } from '@/api/role'
export default {

  components: { treeTable, icons },
  data() {
    return {
      defaultExpandAll: false,
      showCheckbox: true,
      tableLoading:false,
      componentDisabled:true,
      ParentMenu:false,

      // 编辑还是更新
      dialogType: 'edit',
      dialogVisible: false,
      button_loging: false,

      //表单数据
      menusForm :{
         path:'',
         component:'Layout',
         name:'',
         title:'',
         roles:'',
         icon:'',
         pid:0,
         hidden:'0',
         pidName:''
      },

      //角色
      menuRoles:[],

      //验证规格
      rules:{

        title: [
          { required: true, message: '请输入菜单标题', trigger: 'blur' },
        ],

        name: [
          { required: true, message: '请输入路由名称', trigger: 'blur' },
        ],

        path: [
          { required: true, message: '请输入跳转路由', trigger: 'blur' },
        ],
        component: [
          { required: true, message: '请输入组件路径', trigger: 'blur' },
        ],
      },

      columns: [
        {
          label: '标题',
          key: 'title',
          width: 200,
          expand:true,
          align: 'left'
        },
        {
          label: '组件',
          key: 'component',
          align: 'left'
        },
        {
          label: '描述',
          key: 'scope'
        },
        {
          label: '操作',
          width:400,
          key: 'operation'
        }
      ],
      data: []
    }
  },
  watch: {
    showCheckbox(val) {
      if (val) {
        this.columns.unshift({
          label: 'Checkbox',
          checkbox: true
        })
      } else {
        this.columns.shift()
      }
      this.reset()
    }
  },
  methods: {
    reset() {
      ++this.key
    },

    click(scope) {
      const row = scope.row
      const message = Object.keys(row)
        .map(i => {
          return `<p>${i}: ${row[i]}</p>`
        })
        .join('')

      this.$notify({
        title: '详情',
        dangerouslyUseHTMLString: true,
        message: message,
        type: 'success'
      })
    },
    //添加菜单
    menusAdd()
    {
      this.ParentMenu = false
      this.componentDisabled = true
      this.dialogType = 'new'
      this.menusForm.pid = 0
      this.dialogVisible = true
      if(this.$refs['ruleForm'] != undefined)
      {
        this.$refs['ruleForm'].resetFields()
      }
    },

    //编辑菜单
    editMenu(scope)
    {
      const row = scope.row
      this.dialogType = 'edit'
      this.dialogVisible = true
      if(this.$refs['ruleForm'] != undefined)
      {
        this.$refs['ruleForm'].resetFields()
      }
      this.menusForm.path = row.path
      this.menusForm.id = row.id
      this.menusForm.pid = row.pid
      this.menusForm.component = row.component
      this.menusForm.name = row.name
      this.menusForm.title = row.title
      this.menusForm.roles = row.roles.split(',')
      this.menusForm.icon = row.icon
      this.menusForm.pidName = row.pid
      this.menusForm.hidden = row.hidden == '' ? '0' : '1'
      if(row.pid == 0)
      {
        this.ParentMenu = false
        this.componentDisabled = true;
      }else{
        this.ParentMenu = true
        this.componentDisabled = false;
      }
    },

    // 确定
    confirmMenu(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          if (isEdit) {
            this.button_loging = true
            updateMenu(this.menusForm).then(res => {
              this.button_loging = false
              this.dialogVisible = false
              this.$notify({
                title: '修改成功！',
                dangerouslyUseHTMLString: true,
                type: 'success'
              })
              this.getMenuList()
            }).catch(error => {
              this.button_loging = false
            })
          } else {
            this.button_loging = true
            addMenu(this.menusForm).then(res => {
              this.button_loging = false
              const { title, name, component, icon } = this.menusForm
              this.dialogVisible = false
              this.$notify({
                title: '添加成功！',
                dangerouslyUseHTMLString: true,
                message: `
                        <div>标题: ${title}</div>
                        <div>名称: ${name}</div>
                        <div>组件: ${name}</div>
                      `,
                type: 'success'
              })
              this.getMenuList()
            }).catch(error => {
              this.button_loging = false
            })
          }
        } else {
          return false
        }
      })
    },
    //获取菜单列表
    getMenuList()
    {
      this.tableLoading = true;
      menuList().then(res => {
          this.tableLoading = false;
          this.data = res.data.data.menus;
      }).catch(error => {
         this.tableLoading = false;
      })
    },

    //获取icon
    getIcon(data)
    {
      this.menusForm.icon = data.value
    },

    //添加子级
    addChirld(data)
    {
        if(this.$refs['ruleForm'] != undefined)
        {
          this.$refs['ruleForm'].resetFields()
        }
        this.ParentMenu = true
        this.dialogType = 'chirld'
        this.dialogVisible = true
        this.componentDisabled = false
        this.menusForm.pid = data.row.id
        this.menusForm.pidName = data.row.title
        this.menusForm.component = '';
    },

    //删除菜单
    deleteMenu({ $index, row })
    {
      this.$confirm('确认删除该菜单么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.tableLoading = true
          deleteMenu(row.id).then(res => {
            this.tableLoading = false
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getMenuList()
          }).catch(error => {
             this.tableLoading = false
          })
        })
      }
  },
  mounted()
  {
      getRoleShow().then(res => {
          this.menuRoles = res.data;
      });
      this.getMenuList()
  }
}
</script>

<style scoped>
.option-item{
  display: inline-block;
  margin-right: 15px;
}
</style>
